import 'dart:async';

import 'package:color_dart/color_dart.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertz/components/a_button/index.dart';
import 'package:fluttertz/components/a_dialog/a_dialog.dart';
import 'package:fluttertz/utils/global.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Login extends StatefulWidget {
  Login({Key key}) : super(key: key);

  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  SharedPreferences prefs;

  String _username = "";
  String _pwd = "";

  @override
  void initState() {
    super.initState();

    Future.delayed(Duration.zero, () async {
      prefs = await SharedPreferences.getInstance();
      _username = prefs.getString('username');
      _pwd = prefs.getString('pwd');

      if (_username == null) {
        _username = "";
      }
      if (_pwd == null) {
        _pwd = "";
      }

      G.user.uname = _username;

      _controller_username = new TextEditingController(text: _username);
      _controller_pwd = new TextEditingController(text: _pwd);

      setState(() {});

    });

    Future.delayed(Duration(milliseconds: 2000), () async {
      ADialog.alert(context,
          title: '注意事項',
          content:
              '1. 啟用強制消保時，請自行確認機台營運狀況，以免發生爭議!\n2. 機台保夾金額請確實設置，不正確的設定會導致自動消保功能異常!\n3. APP會使用即時的定位位置，排列裝置的順序，不會將定位紀錄用做其他用途!');
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  TextEditingController _controller_username;
  TextEditingController _controller_pwd;

  bool _isloading = false;

  /// 登錄
  login() async {
    _username = _controller_username.text;
    _pwd = _controller_pwd.text;

    // if (_username == null || _username.isEmpty) {
    //   _username = "colin";
    //   _pwd = "123456";
    // }

    if (_username.isEmpty || _pwd.isEmpty) {
      return G.toast('請輸入用户名和密碼！');
    }

    if (_isloading) {
      return;
    }
    _isloading = true;

    /// 登錄前移除user， 不然登錄会提示token错误
    prefs.remove('user');

    try {
      Response response;
      Dio dio = Dio();
      // String url = "https://aps.acciot.com.tw/api/taizhu/login?username=$_username&password=$_pwd";
      // response = await dio.get(url);
      response = await dio
          .post("https://aps.acciot.com.tw/api/taizhu/login", queryParameters: {
        "username": _username,
        "password": _pwd,
        "registration_id": G.user.registration_id
      });

      if (response == null) return null;

      Map<String, dynamic> resCallbackMap = response.data;

      int code = resCallbackMap['code'];
      if (code != 1) {
        G.toast('登錄失敗');
        _isloading = false;
        return null; //返回值不对
      }

      G.user.inittz(resCallbackMap['data'], _username, "");
      prefs.setString('username', _username);
      prefs.setString('pwd', _pwd);

      _isloading = false;
      await G.toast('登錄成功');
      G.pushNamed('/home');
    } catch (e) {
      G.toast('登錄失敗');
      _isloading = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: BoxDecoration(
            image: DecorationImage(
          image: AssetImage("lib/assets/images/tz/bg.png"),
          fit: BoxFit.cover,
        )),
        child: Scaffold(
          backgroundColor: Colors.transparent,
          resizeToAvoidBottomInset: false,
          body: Container(
            color: Colors.transparent,
            padding: EdgeInsets.only(left: 35, right: 35, top: 137),
            child: Column(
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(bottom: 60),
                  width: 94,
                  height: 94,
                  child: Image.asset(
                    'lib/assets/images/logo.png',
                    fit: BoxFit.cover,
                  ),
                ),

                /// 输入用户名
                Container(
                  height: 55,
                  decoration: BoxDecoration(border: G.borderBottom()),
                  child: TextField(
                    keyboardType: TextInputType.text,
                    controller: _controller_username,
                    decoration: InputDecoration(
                        counterText: "",
                        border: InputBorder.none,
                        hintText: "請輸入用户名",
                        hintStyle: TextStyle(
                          fontSize: 14,
                        )),
                    onChanged: (e) {
                      G.user.uname = e;
                      setState(() {});
                    },
                  ),
                ),

                /// 密碼
                Container(
                  height: 55,
                  decoration: BoxDecoration(border: G.borderBottom()),
                  child: Row(
                    children: <Widget>[
                      Flexible(
                        child: TextField(
                          maxLength: 12,
                          controller: _controller_pwd,
                          keyboardType: TextInputType.text,
                          decoration: InputDecoration(
                              counterText: '',
                              border: InputBorder.none,
                              hintText: '請輸入密碼',
                              hintStyle: TextStyle(
                                fontSize: 14,
                              )),
                          onChanged: (e) {
                            setState(() {});
                          },
                        ),
                      ),
                    ],
                  ),
                ),

                Container(
                  height: 55,
                  child: Row(
                    children: <Widget>[
                      AButton.normal(
                        bgColor: Colors.transparent,
                        child: Text('註 冊',
                            style: TextStyle(
                              fontSize: 18,
                              color: rgba(0, 220, 12, 1),
                            )),
                        onPressed: () => G.pushNamed('/regist'),
                      ),
                      Spacer(),
                      AButton.normal(
                        bgColor: Colors.transparent,
                        child: Text('忘記密碼',
                            style: TextStyle(
                              fontSize: 18,
                              color: rgba(250, 1, 0, 1),
                            )),
                        onPressed: () => G.pushNamed('/xgma'),
                      ),
                    ],
                  ),
                ),

                /// 確認
                Container(
                  margin: EdgeInsets.only(top: 20),
                  child: AButton.normal(
                      width: 300,
                      child: Text('登錄',
                          style: TextStyle(
                              fontSize: 18, fontWeight: FontWeight.bold)),
                      // bgColor: rgba(136, 175, 213, 1),
                      type: 'info',
                      color: hex('#fff'),
                      onPressed: () => login()),
                ),
              ],
            ),
          ),
        ));
  }
}
